package com.lzp.java.concurrent.jmm;

/**
 * 验证可见性问题
 *
 * @author lzp
 * @date 2020/02/23
 */
public class FieldVisibility {
    /**
     * 加volatile，可保证a/b的可见性
     */
    private int a = 1;
    private volatile int b = 2;

    private void print() {
        // 非原子操作，打印a后可能有线程切换
        // System.out.println("a = " + a + ", b = " + b);
        System.out.println("b = " + b + ", a = " + a);
    }

    private void update() {
        a = 3;
        b = a;
    }

    public static void main(String[] args) {
        while (true) {
            FieldVisibility instance = new FieldVisibility();
            new Thread(() -> {
                try {
                    // 增大可见性出现的概率
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                instance.update();
            }).start();
            new Thread(() -> {
                try {
                    // 增大可见性出现的概率
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                instance.print();
            }).start();

            // 校验结果
            // if (instance.a == 1 && instance.b == 2) {
            //     break;
            // }
        }
    }
}
